<?php

namespace app\webapi\vms\service;

use app\webapi\common\BaseService;
use app\webapi\vms\model\ChannelModel;
use app\webapi\vms\model\SystemChannelModel;
use library\OWException;

/**
 * @栏目服务类
 */
class CategoryService extends BaseService
{
    /**
     * @desc 获取分类树形列表
     * @param $params
     * @param $website_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/18-11:59
     */
    public function getTreeList($params, $website_id)
    {
        $root_pid = 3;
        if ($params['type'] == 2) {
            $root_pid = 4;
        }
        if ($params['type'] == 3) {
            $root_pid = 5;
        }
        //定义查询条件
        $where = ['website_id' => $website_id, 'root_pid' => $root_pid, 'delete_time' => 0];
        //指定查询字段
        $fields = ['id', 'name', 'pid', 'root_pid', 'system_channel_id'];
        //查询数据
        $list = ChannelModel::field($fields)->where($where)->select()->toArray();
        //提取系统模板id
        $temp_id_arr = array_column($list, 'root_pid');
        //从系统模板中查询栏目的可编辑权限
        $system_channel_info = SystemChannelModel::field(
            ['id', 'is_editable', 'is_removable', 'is_reproducible']
        )->append(['is_editable_text'])->where(['id' => $temp_id_arr])->select()->toArray();
        $is_editable_arr = array_column($system_channel_info, 'is_editable', 'id');
        $is_removable_arr = array_column($system_channel_info, 'is_removable', 'id');
        $is_reproducible_arr = array_column($system_channel_info, 'is_reproducible', 'id');
        foreach ($list as &$v) {
            $v['is_editable'] = $is_editable_arr[$v['system_channel_id']] ?? '';
            $v['is_removable'] = $is_removable_arr[$v['system_channel_id']] ?? '';
            $v['is_reproducible'] = $is_reproducible_arr[$v['system_channel_id']] ?? '';
            unset($v['system_channel_id']);
        }
        unset($v);
        //处理数据为树状结构
        $tree_list = listToTree($list, 'id', 'pid');
        //返回数据
        return $tree_list;
    }

    /**
     * @desc 编辑分类
     * @param $params
     * @param $website_id
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/18-12:00
     */
    public function edit($params, $website_id)
    {
        //检测父级id是否存在
        $pid_info = ChannelModel::field(['id', 'root_pid', 'level'])->where(['website_id' => $website_id, 'id' => $params['pid']])->find();
        if (empty($pid_info)) {
            throw new OWException('父级id不存在', $params['pid']);
        }

        //检测层级限制
        if ($pid_info['level'] > 3) {
            throw new OWException('最多支持三级子目录', $params['pid']);
        }

        //检测名称是否重复
        $check_name = ChannelModel::where(['website_id' => $website_id, 'pid' => $params['pid'], 'name' => $params['name']])->find();
        if (!empty($check_name)) {
            throw new OWException('该目录下已存在相同名称的栏目', $params['name']);
        }

        //查看是否可添加子元素
        $is_reproducible = SystemChannelModel::where(['id' => $pid_info['root_pid']])->value('is_reproducible');

        if (!$is_reproducible && $pid_info['root_pid'] != 0) {
            throw new OWException('该栏目下不可添加子元素', $params['pid']);
        }

        //检测目录下子元素的数量
        $children_item_count = ChannelModel::where(['pid' => $params['pid']])->count();
        if ($children_item_count >= 10) {
            throw new OWException('该栏目下最多只能创建10个元素', $params['pid']);
        }

        if (isset($params['id']) && !empty($params['id'])) {
            ChannelModel::where(['id' => $params['id']])->save(['name' => $params['name']]);
        } else {
            //写入子栏目信息
            $insert = [
                'pid' => $params['pid'],
                'root_pid' => $pid_info['root_pid'],
                'level' => $pid_info['level'] + 1,
                'name' => $params['name'],
                'website_id' => $website_id,
            ];
            (new ChannelModel())->save($insert);
        }

        return true;
    }

    /**
     * @desc 删除分类id
     * @param $id
     * @param $website_id
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/13-11:57
     */
    public function delete($id, $website_id)
    {
        $info = ChannelModel::where(['id' => $id, 'website_id' => $website_id])->find();
        if (empty($info)) {
            throw new OWException('分类id不存在', $id);
        }

        ChannelModel::where(['id' => $id, 'website_id' => $website_id])->update(['delete_time' => time()]);
        return true;
    }

    /**
     * @desc 分类排序
     * @param $json_array
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/13-12:01
     */
    public function sort($pid, $json_array, $website_id)
    {
        $info = ChannelModel::where(['id' => $pid])->find();
        if (empty($info)) {
            throw new OWException('父级id不存在', $pid);
        }
        $where = ['website_id' => $website_id, 'pid' => $pid];
        foreach ($json_array as $v) {
            $where['id'] = $v['id'];
            ChannelModel::where($where)->update(['sort' => $v['sort']]);
        }
        return true;
    }
}